package org.gl.training.planner.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.gl.training.planner.dao.UserDao;
import org.gl.training.planner.model.Constants;
import org.gl.training.planner.model.User;
import org.gl.training.planner.model.UserHistory;
import org.gl.training.planner.model.UserTypes;

@ManagedBean(name = "registerBean")
@RequestScoped
public class RegisterBean {

	private User user = new User();

	@ManagedProperty(value = "#{userDao}")
	private UserDao userDao;

	private String errorMessage;

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public String register() {
		if (StringUtils.isEmpty(user.getUserName())) {
			errorMessage = "Username is empty";
			return null;
		} else if (StringUtils.isEmpty(user.getFullName())) {
			errorMessage = "Fullname is empty";
			return null;
		} else if (StringUtils.isEmpty(user.getEmail())) {
			errorMessage = "E-mail is empty";
			return null;
		}else if (!EmailValidator.getInstance().isValid(user.getEmail())){
			errorMessage = "E-mail is invalid";
			return null;
		}
		else if (StringUtils.isEmpty(user.getPassword())) {
			errorMessage = "Password is empty";
			return null;
		} else if (StringUtils.isEmpty(user.getConfirmPassword())) {
			errorMessage = "ConfirmPassword is empty";
			return null;
		} else if (!user.getPassword().equals(user.getConfirmPassword())) {
			errorMessage = "Passwords don't match";
			return null;
		} else if (userDao.getUser(user.getUserName()) != null) {
			errorMessage = "Username is already registered";
			return null;
		}

		List<UserTypes> userTypes = new ArrayList<UserTypes>();
		userTypes.add(UserTypes.USER);
		user.setUserTypesList(userTypes);

		user.setUserStatus(Constants.USER_STATUS_WAITING);

		List<UserHistory> userHistoryList = new ArrayList<UserHistory>();
		UserHistory userHistory = new UserHistory();
		userHistory.setTime(new Date());
		userHistory.setAction("User just registered");
		userHistory.setUser(user);
		user.setUserHistoryList(userHistoryList);
		userHistoryList.add(userHistory);

		userDao.save(user);
		return "success";
	}
}
